<template>
  <v-dialog v-model="dialogFormVisible" fullscreen persistent class="ma-4">
    <v-card>
      <v-card-title class="text-h5">{{ title }}</v-card-title>
      <v-card-text>
        <div class="generator-main rounded-lg elevation-10">
          <div class="generator-el-steps rounded-lg elevation-10">
            <v-stepper v-model="active" :vertical="direction === 'vertical'" class="steps">
              <v-stepper-item v-for="(step, index) in flagObjArray" :key="index" :value="step.flag" :title="step.title"
                :complete="active > step.flag" />
            </v-stepper>
          </div>
          <div class="generator-steps rounded-lg elevation-10">
            <TableDataStep :base-dict-data="baseDictData" :base-form="baseForm" :table-form="tableForm" :active="active"
              :min-flag="minFlag" :max-flag="maxFlag" :dict="dict" @inform-flag="informFlag" @inform-data="informData"
              @change-step="handleSetStep" @close="close" @submit="save" />
            <FrontendStep :base-dict-data="baseDictData" :base-form="baseForm" :table-form="tableForm" :active="active"
              :min-flag="minFlag" :max-flag="maxFlag" :dict="dict" @inform-flag="informFlag" @inform-data="informData"
              @change-step="handleSetStep" @close="close" @submit="save" />
            <BackendStep :base-dict-data="baseDictData" :base-form="baseForm" :table-form="tableForm" :active="active"
              :min-flag="minFlag" :max-flag="maxFlag" :dict="dict" @inform-flag="informFlag" @inform-data="informData"
              @change-step="handleSetStep" @close="close" @submit="save" />
          </div>
        </div>
      </v-card-text>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, watch } from 'vue';
import TableDataStep from './step/TableDataStep.vue';
import BackendStep from './step/BackendStep.vue';
import FrontendStep from './step/FrontendStep.vue';
import { doInsert, doUpdate, getSubList } from '@/api/generator/tableManagement';
import { isNull } from '@/utils/validate';
import { deepClone } from '@/utils/clone';
import { message } from '@/utils/message';
import { getDictList } from '@/utils/dict';

const dialogFormVisible = ref(false);
const direction = ref('horizontal');
const active = ref(1);
const minFlag = ref(1);
const maxFlag = ref(1);
const flagObjArray = ref<any[]>([]);
const flagArray = ref<number[]>([]);
const baseDictData = ref<any>({});
const queryForm = ref<any>({});
const baseForm = ref<any>({ jdbcType: 'mysql' });
const tableForm = ref<any[]>([]);
const backupStepData = ref<any>({});
const dict = ref<any>({});
const title = ref('');
const loading = ref(false);

const emit = defineEmits(['fetchData']);

// 屏幕宽度检测
function screenWidth(val: number) {
  direction.value = val >= 992 ? 'horizontal' : 'vertical';
}

// 初始化字典 - 使用异步方式正确获取字典数据
async function initDict() {
  try {
    dict.value.table_type = await getDictList('table_type');
    dict.value.jdbc_type = await getDictList('jdbc_type');
    dict.value.java_data_type = await getDictList('java_data_type');
    dict.value.show_type = await getDictList('show_type');
    dict.value.validate_type = await getDictList('validate_type');
    dict.value.query_type = await getDictList('query_type');
  } catch (error) {
    console.error('初始化字典失败:', error);
  }
}

// 显示编辑弹窗
async function showEdit(row?: any) {
  // 首先初始化字典数据
  await initDict();

  if (!row) {
    title.value = '代码生成 - 添加';
    baseForm.value = { jdbcType: 'mysql' };
  } else {
    title.value = '代码生成 - 编辑';
    baseForm.value = Object.assign({}, row);
    queryForm.value.id = baseForm.value.id;
    fetchData();
  }
  dialogFormVisible.value = true;
}

// 关闭弹窗
function close() {
  dialogFormVisible.value = false;
  active.value = 1;
  flagArray.value = [];
  baseForm.value = { jdbcType: 'mysql' };
  tableForm.value = [];
  queryForm.value = {};
  backupStepData.value = {};
  flagObjArray.value = [];
}

// 上报Flag号
function informFlag(flag: number, flagTitle: string) {
  const temp = { flag, title: flagTitle };
  flagObjArray.value.push(temp);
  flagArray.value.push(flag);

  minFlag.value = Math.min(...flagArray.value);
  maxFlag.value = Math.max(...flagArray.value);
  active.value = minFlag.value;
  flagObjArray.value.sort((a, b) => a.flag - b.flag);
}

// 执行步骤
function handleSetStep(stepActive: number, stepBaseForm?: any, stepTableForm?: any) {
  nextTick(() => {
    const futureActive = active.value + stepActive;

    if (futureActive > active.value) {
      // 记录上次步骤
      backupStepData.value[active.value] = {
        baseForm: deepClone(baseForm.value),
        tableForm: deepClone(tableForm.value),
      };

      if (stepBaseForm) {
        baseForm.value = deepClone(stepBaseForm);
      }
      if (stepTableForm && stepTableForm.length > 0) {
        const tmpForm = stepTableForm.sort((a: any, b: any) => a.sort - b.sort);
        tableForm.value = deepClone(tmpForm);
      }
    } else {
      const bygoneActive = backupStepData.value[futureActive];
      if (bygoneActive) {
        if (bygoneActive.baseForm) {
          baseForm.value = deepClone(bygoneActive.baseForm);
        }
        if (bygoneActive.tableForm && bygoneActive.tableForm.length > 0) {
          const tmpForm = bygoneActive.tableForm.sort((a: any, b: any) => a.sort - b.sort);
          tableForm.value = deepClone(tmpForm);
        }
      }
    }

    // 执行保存操作
    if (futureActive > maxFlag.value) {
      save();
    } else {
      active.value = futureActive;
      const tmpTableForm = deepClone(tableForm.value);
      tableForm.value = [];
      setTimeout(() => {
        tableForm.value = deepClone(tmpTableForm);
      }, 50);
    }
  });
}

// 保存
async function save() {
  loading.value = true;
  try {
    // 字段数据
    const tmpForm = deepClone(baseForm.value);
    // 字段数据
    const columnList = deepClone(tableForm.value);

    // 处理数据
    for (let i = 0; i < columnList.length; i++) {
      delete columnList[i].disabled;
      if (!isNull(columnList[i].izPk)) {
        columnList[i].izPk = columnList[i].izPk + '';
      }
      if (!isNull(columnList[i].izNotNull)) {
        columnList[i].izNotNull = columnList[i].izNotNull + '';
      }
      if (!isNull(columnList[i].izShowList)) {
        columnList[i].izShowList = columnList[i].izShowList + '';
      }
      if (!isNull(columnList[i].izShowForm)) {
        columnList[i].izShowForm = columnList[i].izShowForm + '';
      }
      if (!isNull(columnList[i].validateType)) {
        columnList[i].validateType = columnList[i].validateType.join(',');
      }
    }

    if (columnList.length === 0) {
      tmpForm.columnList = null;
    } else {
      tmpForm.columnList = columnList;
    }

    // 修改或新增
    if (!isNull(tmpForm.id)) {
      const response = await doUpdate(tmpForm);
      message.success(response.data?.msg || '更新成功');
    } else {
      const response = await doInsert(tmpForm);
      message.success(response.data?.msg || '保存成功');
    }

    close();
    emit('fetchData');
  } catch (error) {
    message.error('保存失败');
  } finally {
    loading.value = false;
  }
}

// 上报数据
function informData(data: any) {
  baseDictData.value = data;
}

// 请求数据
async function fetchData() {
  loading.value = true;
  try {
    const { data } = await getSubList(queryForm.value);
    if (!isNull(data)) {
      if (!isNull(data.columnList)) {
        tableForm.value = [];
        // 处理数据
        for (let i = 0; i < data.columnList.length; i++) {
          tableForm.value.push(data.columnList[i]);

          if (!isNull(tableForm.value[i].izPk)) {
            tableForm.value[i].izPk = parseInt(tableForm.value[i].izPk);
          }
          if (!isNull(tableForm.value[i].izNotNull)) {
            tableForm.value[i].izNotNull = parseInt(tableForm.value[i].izNotNull);
          }
          if (!isNull(tableForm.value[i].izShowList)) {
            tableForm.value[i].izShowList = parseInt(tableForm.value[i].izShowList);
          }
          if (!isNull(tableForm.value[i].izShowForm)) {
            tableForm.value[i].izShowForm = parseInt(tableForm.value[i].izShowForm);
          }
          if (!isNull(tableForm.value[i].validateType)) {
            tableForm.value[i].validateType = tableForm.value[i].validateType.split(',');
          }
        }
      }
    }
  } catch (error) {
    message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
}

// 响应屏幕宽度变化
screenWidth(window.innerWidth);
window.addEventListener('resize', () => {
  screenWidth(window.innerWidth);
});

defineExpose({ showEdit });
</script>

<style lang="scss">
.generator-main {
  position: relative;

  .generator-el-steps {
    max-height: 160px;
    margin-bottom: 20px;
  }

  .generator-steps {
    position: relative;
    z-index: 999;
    width: 100%;
  }

  .steps {
    margin-bottom: 10px;
  }

  .move-btn {
    cursor: grab;
  }

  .step-main {
    .step-content {
      position: relative;
      height: 540px;
      overflow-x: hidden;
      overflow-y: auto;
    }

    .step-footer {
      position: relative;
      box-sizing: border-box;
      display: grid;
      width: 100%;
      padding: 20px 0;
      overflow: hidden;
      text-align: right;
      border-top: 1px solid #dcdfe6;
    }
  }
}
</style>
